package com.fresh.common.interceptor;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fresh.common.annotation.IgnoreAuth;
import com.fresh.utils.CookieManager;
import com.fresh.utils.Response;
import com.fresh.utils.ServletUtil;

/**
 * 权限(Token)验证
 * 
 * @author alex
 * @email gaonan.service@gmail.com
 * @date 2017-03-23 15:38
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	private final Pattern allowedMethods = Pattern.compile("^(POST)$");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		IgnoreAuth annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
		} else {
			return true;
		} 
		// 如果有@IgnoreAuth注解，则不验证token
		if (annotation != null) {
			return true; 
		} 
		// 从header中获取token 
		Object token = request.getSession().getAttribute("LOGIN_FLAG");
		// 如果header中不存在token，则从参数中获取token
		if (token!=null) { 
			return true;
		}else{
			writeMessage(request, response);
		}
		return true;
	}

	private void writeMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
			 response.sendRedirect(request.getContextPath()+"/invalid");
	}

}
